#! /usr/bin/env python
#coding=utf-8
import re
from string import Template
import sys
import os
import argparse

def parse_args():
    parse = argparse.ArgumentParser(description='Automatically generates bbappend files.')  
    parse.add_argument('-s', '--spec', required=True, type=str, help='Enter the address of the spec file (Required)')  
    parse.add_argument('-b', '--bb',  type=str, help='Enter the address of the bb file')
    args = parse.parse_args()  
    return args 

#search file
def getFilepath(rootDir,filepathmsg,filetype):

    filepathresult = []

    for dirpath,dirNames,fileNames in os.walk(rootDir):

        for fileName in fileNames:

            apath = os.path.join(dirpath ,fileName)
            apathname = os.path.splitext(apath)[0]
            apathtype = os.path.splitext(apath)[1]
            #for i in range(len(filetype)):
            for i in filetype:

                if i in apathtype:

                    #for j in range(len(filepathmsg)):
                    for j in filepathmsg:
                        if j in apathname:
                            filepathresult.append(apath)

    if len(filepathresult) == 1:
        dir = filepathresult[0]
        print(dir)
    if len(filepathresult) != 1:  
        for i in range(len(filepathresult)):
            print(filepathresult[i])
        dir = None
    return dir


#get remote package address
def readSRC_URI(bbfilename):
    f = open(bbfilename)
    count = -1
    for count, line in enumerate(f.readlines()):
        count += 1
        if line.find('SRC_URI = "') != -1: 
            remote_url = line.strip('SRC_URI = "')
            remote_url = remote_url.split('"')[0].strip()#Delete the '"' at the end
            remote_url = remote_url.split("\\")[0].strip()#Delete the ' \' at the end
    return remote_url

def existbbfile(repo_name):
    global bb_source, bbfilename
    if getFilepath("/usr1/src/yocto-poky",[repo_name],[".bb"]) != None:
        print("Find the following bb file in yocto poky:")
        bbDir = getFilepath("/usr1/src/yocto-poky",[repo_name],[".bb"])
        (bbfile_path, bbfilename) = os.path.split(bbDir)
        bb_source = "/yocto-poky"+bbDir.split("yocto-poky")[1].strip()

    if getFilepath("/usr1/src/yocto-poky",[repo_name],[".bb"]) == None:
        print(args.bb)
        if args.bb == None:
            print("\033[31m[ERROR] : bb file not found in /yocto-poky! Please enter the bb file absolute address by args [-b BB]\033[0m")
            #bbDir = input()
            bbDir = args.bb
        else:
            bbDir = args.bb
            (bbfile_path, bbfilename) = os.path.split(bbDir)
            bb_source = "From remote repository(need to change manually)."
    url = readSRC_URI(bbDir)
    return url




    
def readpatch(filename):
    file = open(filename)
    lines = file.readlines()
    result = []
    for i in lines:
        if re.search('^Patch[0-9]', i):
            result.append(i)
    m = '		   file://'
    a = r"\one"
    result2 = []
    for i in result:
        i = i.split()
        result2.append(m +i[-1]+ ' '+a[0])
    str = "\n".join(result2)
    str = str.strip("		   ")#delate the  '		   ' at the beginning
    return str









class BuildData:
 
    def Init(self):
        
 
        mycode = []
 

        #print("Please enter the spec file absolute address:")
        #spec_dir = input()
        spec_dir = args.spec

        # (file, ext) = os.path.splitext(spec_dir)
        # print(file)
        # print(ext)

        (repo_path, filename) = os.path.split(spec_dir)
        print("spec file name:",filename)

        repo_name = repo_path.split("/")[-1].strip()
        print("repository name:",repo_name)


        print("Looking for package ......")
        print("The following packages were found:")
        package_dir = getFilepath(repo_path,[repo_name],[".tar",".gz",".bz2",".xz"])
        (package_path, packagename) = os.path.split(package_dir)




        print("Looking for bb file ......")
        url = existbbfile(repo_name) #Read the original remote address of the package
        getFilepath("/usr1/src/yocto-poky",[repo_name],[".bb"])


        

 
        # import template
        template_file = open('bbappend.tmpl', 'r')
        tmpl = Template(template_file.read())
 
 
        
    	# read spec file
        f = open(spec_dir)
        count = -1
        for count, line in enumerate(f.readlines()):
            count += 1
            if line.find('Name:') != -1: name = line.split(":")[1].strip()
            if line.find('Version:') != -1: version = line.split(":")[1].strip()
            # if line.find('Source0:') != -1: package = "file://"+line.split("/")[-1].strip().replace("%{version}", "${PV}")
            
            

    	
        # replace template
        mycode.append(tmpl.substitute(
            BBDIR = bb_source,
            Name = repo_name,
            Version = version,
            REMOTE_URI = url,
            PATCH = readpatch(spec_dir),
            LOCAL_URI = "file://"+packagename,
            WORKDIR = '${WORKDIR}',
            PV = '${PV}',
            BP = '${BP}',
            BPN = '${BPN}',
            ))
 
        # Write code to file
        filePath = './'+bbfilename.split(".")[0].split("_")[0]+'_%.bbappend'
        class_file = open(filePath, 'w')
        class_file.writelines(mycode)
        class_file.close()
 
        print('Generated successfully!')
 
if __name__ == '__main__':

    
    args = parse_args()	
    build = BuildData()
    build.Init()
